#include <iostream>
#include <cstring>
#include "Log.hpp"
#include "InetAddr.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "ThreadMod.hpp"

using namespace LogModule;
using namespace ThreadModule;

int socketfd = 0;
std::string ip;
uint16_t port = 0;
pthread_t tid;
void Recv()
{
    while (true)
    {
        // 收消息
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;

        // 如果UDPClient和UDPServe传入的ip地址不一样，程序会阻塞在此
        int m = recvfrom(socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            // buffer[m] = 0;
            // // std::cerr << "\r"<<buffer << std::endl;
            // std::cerr <<buffer<<std::endl;
            // // std::cout << "please enter#"<<std::flush;
            buffer[m] = 0;
            // 1. 先回到行首
            std::cout << "\r";
            // 2. 清除当前行
            std::cout << std::string(80, ' ');  // 80 是一个估计的行宽
            // 3. 再次回到行首
            std::cout << "\r";
            // 4. 打印收到的消息
            std::cout << buffer << std::endl;
            // 5. 重新打印输入提示
            std::cout << "please Enter#" << std::flush;
        }
    }
}
void Send()
{
    struct sockaddr_in client;
    memset(&client, 0, sizeof(client));
    client.sin_port = htons(port);
    client.sin_addr.s_addr = inet_addr(ip.c_str());
    client.sin_family = AF_INET;
    int count=1;
    while (true)
    {
        std::string input;
        // if(count==1)
        // {
            std::cout<<"please Enter#";
            // count=0;
        // }
        std::getline(std::cin, input);
        
        // input+='\n';
        int n = sendto(socketfd, input.c_str(), input.size(), 0, (struct sockaddr *)&client, sizeof(client));
        // std::cout<<std::endl;
        if(input=="QUIT")
        {
            pthread_cancel(tid);
            break;
        }
        if (n < 0)
        {
            LOG(FATAL) << "send error";
        }
        
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " serve_ip serveport" << std::endl;
        return 1;
    }
    ip = argv[1];
    port = std::stoi(argv[2]);

    // 创建socketfd
    socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
        LOG(FATAL) << "soketfd create error";
        return 2;
    }

    Thread recver(Recv);
    Thread sender(Send);

    recver.start();
    sender.start();

    tid=recver.ID();

    recver.join();
    sender.join();

    return 0;
}
